﻿using NewRen.Helpers;
using NewRen.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;

namespace NewRen.Areas.Admin.Controllers
{
    [Schema.LoginCheck]
    [RouteArea("NewRen")]
    public class NewRenController : BaseController
    {

        // GET: Admin/NewRen
        public ActionResult Index(string key, DateTime? Begin, DateTime? End, int p = 0)
        {
            IEnumerable<User> query = db.Users.AsEnumerable();
            if (!string.IsNullOrEmpty(key))
            {
                query = query.Where(c => c.UserName.Contains(key));
            }
            if (Begin.HasValue)
            {
                query = query.Where(c => c.AddTime >= Begin);
            }
            if (End.HasValue)
            {
                query = query.Where(c => c.AddTime <= End);
            }
            query = query.OrderByDescending(x => x.AddTime);
            ViewBag.PageInfo = PagerHelper.Do(ref query, 50, p);
            return View(query);
        }


        [HttpPost]
        [NewRen.Schemas.ValidateSID]
        public ActionResult Delete(int id)
        {
            try
            {
                Models.User user = new Models.User();
                user = db.Users.Find(id);
                db.Users.Remove(user);
                db.SaveChanges();
                return Content("ok");
            }
            catch
            {
                return Content("fail");
            }
        }


        [HttpGet]
        public ActionResult Show(int id)
        {
            Models.User user = new Models.User();
            user = db.Users.Find(id);
            ViewBag.User = user;
            return View();
        }


        [HttpGet]
        public ActionResult Edit(int id)
        {
            var user = db.Users.Find(id);
            ViewBag.User = user;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(User model)
        {
            if (ModelState.IsValid)
            {
                try
                {

                    var user = db.Users.Where(u => u.UserName == model.UserName && u.ID != model.ID).FirstOrDefault();
                    if (user == null)
                    {
                        user = db.Users.Find(model.ID);
                        user.UserName = model.UserName;
                        user.RealName = model.RealName;
                        user.Phone = model.Phone;
                        user.Address = model.Address;
                        user.Job = model.Job;
                        user.Email = model.Email;
                        user.QQ = model.QQ;
                        user.WhatApp = model.WhatApp;
                        db.SaveChanges();
                        return Redirect("/Admin/NewRen/Index");
                    }
                    else
                    {
                        ModelState.AddModelError("", "该用户名已经存在！");
                    }
                }
                catch
                {
                    ModelState.AddModelError("", "修改出错");
                }
            }
            else
            {
                ModelState.AddModelError("", "信息填写错误");
            }
            return View();
        }


        #region 修改优先级
        /// <summary>
        /// 修改优先级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult PriorityEdit(int id)
        {
            var user = db.Users.Find(id);
            ViewBag.User = user;
            return View();
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PriorityEdit(int ID, int Priority)
        {
            var user = db.Users.Find(ID);
            user.Priority = Priority;
            db.SaveChanges();

            return Redirect("/Admin/NewRen/Index");
        }
        #endregion


        #region 修改认证
        /// <summary>
        /// 修改认证
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyEdit(int id)
        {
            var user = db.Users.Find(id);
            return View(user);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult VerifyEdit(int ID, bool IsVerifed)
        {
            var user = db.Users.Find(ID);
            try
            {
                user.IsVerified = IsVerifed;
                db.SaveChanges();
                return Redirect("/Admin/NewRen/Index");
            }
            catch
            {
                ModelState.AddModelError("", "修改出错，请重试！");
                return View(user);
            }

        }
        #endregion

        /// <summary>
        ///  
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            var cities = db.Cities.ToList();
            var jobs = db.Jobs.ToList();
            var pictures = db.Pictures.ToList();
            ViewBag.Cities = cities;
            ViewBag.Pictures = pictures;
            ViewBag.Jobs = jobs;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Add(User model, string spicture,HttpPostedFileBase file)
        {
            var cities = db.Cities.ToList();
            var pictures = db.Pictures.ToList();
            ViewBag.Cities = cities;
            ViewBag.Pictures = pictures;
            try
            {
                var user = db.Users.Where(u => u.UserName == model.UserName).FirstOrDefault();
                if (user != null)
                {
                    ModelState.AddModelError("", "该用户名已经存在");
                }
                else
                {
                    if (file != null)
                    {
                        System.IO.Stream stream = file.InputStream;
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, (int)stream.Length);
                        stream.Close();
                        model.Picture = buffer;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(spicture))
                        {
                            var phicyPath = HostingEnvironment.MapPath(spicture);
                            FileStream fs = new FileStream(phicyPath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                            int streamLength = (int)fs.Length;
                            byte[] buffer = new byte[streamLength];
                            fs.Read(buffer, 0, streamLength);

                            model.Picture = buffer;
                        }
                    }
                    model.Password = Helpers.Encryt.GetMD5("123456");
                    model.AddTime = DateTime.Now;
                    model.Priority = 0;
                    db.Users.Add(model);
                    db.SaveChanges();
                    return Redirect("/Admin/NewRen/Index");
                }
            }
            catch
            {
                ModelState.AddModelError("", "添加牛人错误");
            }
            return View();
        }


        /// <summary>
        /// 牛人信息统计
        /// </summary>
        /// <returns></returns>
        public ActionResult Stat()
        {
            var now = DateTime.Now;
            var total = db.Users.Count();
            var todayTotal = db.Users.Where(u => u.AddTime.Value.Year == now.Year && u.AddTime.Value.Month == now.Month && u.AddTime.Value.Day == now.Day).Count();
            ViewBag.Total = total;
            ViewBag.TodayTotal = todayTotal;
            return View();
        }


        /// <summary>
        /// 设置显示状态
        /// </summary>
        /// <returns></returns>
        public ActionResult SetShow(int id)
        {
            try
            {
                var user = db.Users.Find(id);
                if (user.IsShow)
                {
                    user.IsShow = false;
                }
                else
                {
                    user.IsShow = true;
                }
                db.SaveChanges();
                return Redirect("/Admin/NewRen/Index");
            }
            catch
            {
                return Redirect("/Admin/Shared/Info?msg=修改牛人显示信息失败");
            }
        }
    }
}